package cn.xny.pet.service.impl;

import cn.xny.basic.exception.BusinessException;
import cn.xny.basic.service.BaiduAiAuditService;
import cn.xny.basic.util.*;
import cn.xny.order.domain.OrderPetAcquisition;
import cn.xny.order.mapper.OrderPetAcquisitionMapper;
import cn.xny.org.domain.Employee;
import cn.xny.org.domain.Shop;
import cn.xny.org.mapper.EmployeeMapper;
import cn.xny.org.mapper.ShopMapper;
import cn.xny.pet.domain.SearchMasterMsg;
import cn.xny.pet.domain.SearchMasterMsgAuditLog;
import cn.xny.pet.dto.MsgDto;
import cn.xny.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.xny.pet.mapper.SearchMasterMsgMapper;
import cn.xny.pet.query.SearchMasterMsgQuery;
import cn.xny.pet.service.SearchMasterMsgService;
import cn.xny.basic.service.impl.BaseServiceImpl;
import cn.xny.user.domain.Logininfo;
import cn.xny.user.domain.User;
import cn.xny.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {

    @Autowired
     private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private BaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;




    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {

           //1.添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user=  userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
          //2.百度智能审核
        Boolean aBoolean = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean aBoolean1 = baiduAiAuditService.imageAudit(msg.getResources());
        if(aBoolean && aBoolean1){
           //修改状态
            msg.setState(1);
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
           //获取距离用户最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());

            if(nearestShop!=null){//找到了店铺
                msg.setShopId(nearestShop.getId());
               //发消息给店铺
                //SmsUtils.sendSms(nearestShop.getTel()+"");
            }else {//附近店铺大于50公里
                msg.setState(3);
                //发消息给用户
              //  SmsUtils.sendSms("")
                System.out.println("你附近暂时没有店铺");
            }
              searchMasterMsgMapper.update(msg);

              return new AjaxResult();
        }else {//审核不通过
            SearchMasterMsgAuditLog log= new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);

            System.out.println("你的发布信息审核失败");

            searchMasterMsgMapper.del(msg.getId());

            return AjaxResult.me().setSuccess(false).setMsg("审核失败");

        }



    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理的寻主消息
        query.setState(1);
        //用于区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        //如果shopId is null = 平台管理员
        query.setShopId(employee.getShop_id());

        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
         query.setState(3);

        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
       query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
      Employee employee= employeeMapper.loadByLogininfoId(logininfo.getId());
         if(employee.getShop_id()!=null){
             query.setShopId(employee.getShop_id());

         }

        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息-设置User_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());

        return super.pageQuery(query);
    }

    //拒单
    @Override
    public void reject(Long id) {

        searchMasterMsgMapper.reject(id);

    }

    //接单
    @Override
    public void accept(MsgDto msgDto) {
        OrderPetAcquisition  order=orderPetAcquisitionMapper.loadBYMsgId(msgDto.getMsgId());

       //判断订单是否存在-和订单状态
        if (order!=null && order.getState()==0){//有订单了，并且是待处理
            throw new BusinessException("订单正在处理，请勿重复接单");
        }
        //生成订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadByAll(msgDto.getMsgId());

        OrderPetAcquisition newOrder = createOrder(msg,msgDto);

        orderPetAcquisitionMapper.save(newOrder);
        //告诉处理人发送短信
        // Employee employee = employeeMapper.loadByAll(msgDto.getHandler());
       // SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在"+msg.getAddress()+"接回宠物");


    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order= new OrderPetAcquisition();
           order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
           order.setDigest(msgDto.getNote());
           order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
           //order.setState(0);
           //order.setPaytype();
          //order.setPetId();
        order.setPrice(msg.getPrice());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
       return order;
    }

}
